<?php

class Product_model extends CI_Model {

	public $id;
	public $name;
	public $price;
	public $priceCurrency;
	public $discount;
	public $discountCurrency;
	public $featured;
	public $storeId;
	public $sku;
	public $description;
	public $stock;
	public $url;
	public $image;
	public $length;
	public $width;
	public $height;
	public $weight;
	
	public function listProducts() {
		return $this->db->get('products')->result();
	}
	
	public function listRecentCheckedout()	{
		$this->db->select('products.*, orders.since');
		$this->db->from('products');
		$this->db->join('orders', 'orders.productId = products.id');
		$this->db->order_by('orders.since');
		$this->db->limit(8);
		return $this->db->get()->result();
	}

	public function listFeaturedProducts($page = 0, $storeId = null)	{
		if ($storeId != null)
			$this->db->where('storeId', $storeId);
		$this->db->order_by('id DESC');
		$this->db->where('featured', 1);
		$query = $this->db->get('products', 10, $page*10);
		return $query->result();
	}
	
	public function listByStore($storeId, $page=0)	{
		$this->db->order_by('id DESC');
		$this->db->where('storeId', $storeId);
		$query = $this->db->get('products', 8, $page*8);
		return $query->result();
	}
	
	public function listByTag($tagId, $page=0)	{
		$this->db->join('producttags', 'producttags.productId = products.id');
		$this->db->where('producttags.tagId', $tagId);
		$query = $this->db->get('products', 16, $page*16);
		return $query->result();
	}
	
	public function listNewest($page=0)	{
		$this->db->order_by('id DESC');
		$query = $this->db->get('products', 8, $page*8);
		return $query->result();
	}
	
	public function addNew()	{
		$this->featured = 0;
		$this->stock = 0;
		$this->description = "";
		$result = $this->db->insert('products', $this);
		if ($result)	{
			return $this->db->insert_id();
		}
		return false;
	}
	
	public function search($sku, $storeId)	{
		$this->db->where('sku', $sku);
		$this->db->where('storeId', $storeId);
		$query = $this->db->get('products', 1);
		$result = $query->result();
		if (count($result) > 0)	{
			return $result[0];
		}
		return null;
	}

	public function getById($id){
		$this->db->where('id', $id);
		$query = $this->db->get('products', 1);
		$result = $query->result();
		if (count($result) > 0)	{
			return $result[0];
		}
		return null;
	}
}

?>